package com.qf.controller;/*
 *保护你的大熊
 *2021/11/22
 *22:40
 */

import com.qf.utils.Result;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

//@Controller
//@ResponseBody
@RestController
public class SysUserController {

    @RequestMapping("/doLogin")
    public Result doLogin(
            String username,
            String password,
            @RequestParam(name = "rememberMe" ,required = false , defaultValue = "false") boolean rememberMe){
        //获取subject
        Subject subject = SecurityUtils.getSubject();
        //创建啊token对象
        UsernamePasswordToken token = new UsernamePasswordToken(username,password,rememberMe);
        try {
            //执行登录操作
            subject.login(token);
            System.out.println(subject.isAuthenticated() ? "已认证":"认证失败");

            System.out.println(subject.hasRole("管理员") ? "拥有管理员角色" : "没拥有管理员角色");
            System.out.println(subject.hasRole("开发工程师") ? "拥有开发工程师角色" : "没拥有开发工程师角色");

            System.out.println(subject.isPermitted("sys:user:add") ? "拥有用户添加权限" : "没拥有用户添加权限");
            System.out.println(subject.isPermitted("sys:kaoqing:add") ? "拥有考勤添加权限" : "没拥有考勤添加权限");
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            return Result.error("未知的用户信息");
        }catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            return Result.error("密码错误");
        }catch (LockedAccountException e) {
            e.printStackTrace();
            return Result.error("账户已锁定");
        }catch (AuthenticationException e){
            e.printStackTrace();
            return Result.error("认证失败");
        }

        return Result.ok();
    }

    @RequestMapping("/logout")
    public Object logout(){
        Subject subject = SecurityUtils.getSubject();
        //执行退出功能，并清除session
        subject.logout();
        return Result.ok("退出成功");
    }
}
